package com.bacel.nb.product.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bacel.nb.product.core.domain.*;
import com.bacel.nb.product.core.dto.ListGageModule;
import com.bacel.nb.product.core.service.*;
import com.bacel.nb.product.web.template.ViewModel.FreeMarkerView;
import com.bacel.nb.product.web.util.DeviceCache;
import com.bacel.nb.product.web.util.MD5ArithmeticUtils;
import com.bacel.nb.product.web.util.RedisPoolUtils;
import com.bacel.nb.product.web.util.WebUtilify;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by Bacel on 2017/04/16.
 */
@RestController
@RequestMapping(value = "/sysmanage/device", produces = "text/html;charset=UTF-8")
public class deviceController {
    private final Logger logger = Logger.getLogger(deviceController.class);

    @Autowired
    private IDeviceService moduleService;

    @Autowired
    private ISysmoduleService sysmoduleService;
    @Autowired
    private ILogsService logsService;
    @Autowired
    private IAppService appService;
    @Autowired
    private IDevicedataService devdataService;
    @Autowired
    private IDevicetypeService devicetypeService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public final ModelAndView list(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        String path = request.getContextPath();
        String menulist = WebUtilify.BuildMenuinfo(path, sysmoduleService);
        // 显示首页
        ModelAndView mav = new FreeMarkerView("device/list", "设备信息", path, menulist, session);
        return mav;
    }
    @RequestMapping(value = "/typelist", method = RequestMethod.GET)
    public final ModelAndView typelist(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        String path = request.getContextPath();
        String menulist = WebUtilify.BuildMenuinfo(path,sysmoduleService);
        // 显示首页
        ModelAndView mav = new FreeMarkerView("device/typelist", "第三方业务平台信息", path, menulist, session);
        return mav;
    }


    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public final ModelAndView add(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        String ports = String.valueOf(request.getServerPort());
        if (!ports.equals("80")) {
            ports = ":" + ports;
        }
        String basePath = request.getScheme() + "://" + request.getServerName() + ports;
        // 显示首页
        ModelAndView mav = new FreeMarkerView("device/add", "设备编辑", "", basePath + "/sysmanage/device/list", session);
        // 显示首页
        //ModelAndView mav = new FreeMarkerView("device/add", "编辑");
        return mav;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String edit(@RequestBody Device module, final HttpServletRequest request) throws IOException {
        String ret = "";
        String errstr = "";
        if (module != null && module.getDevicename() != null) {

            if (module.getCreatedate() == null)
                module.setCreatedate(new Timestamp(System.currentTimeMillis()));
            Device device = moduleService.get(module.getSn());
            if (device != null) {
                device.setDevicename(module.getDevicename());
                device.setLocation(module.getLocation());
                device.setImei(module.getImei());
                device.setCreatedate(module.getCreatedate());
                device.setDeviceinfo(module.getDeviceinfo());
                device.setSim(module.getSim());
                device.setLat(module.getLat());
                device.setLng(module.getLng());
                device.setAppByAppid(module.getAppByAppid());
                device.setDeviceownerByOwnerid(module.getDeviceownerByOwnerid());
                device.setDevicetypeByDevicetypeid(module.getDevicetypeByDevicetypeid());
                this.moduleService.updateT(device);
            } else {
                this.moduleService.insertT(module);
            }
            try {
                Device dev = moduleService.get(module.getSn());
                if (dev.getAppByAppid() != null) {
                    App app = appService.get(dev.getAppByAppid().getId());
                    Jedis redis = RedisPoolUtils.getJedisObject();
                    Pipeline p = redis.pipelined();
                    Map<String, String> data = new HashMap<>();
                    data.put(dev.getSn(), app.getPushaddress());
                    p.hmset("deviceinfo", data);
                    p.sync();
                    p.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Syslog log = new Syslog();
            log.setTitle("修改设备信息");
            log.setSysuserByUserid(WebUtilify.LoginUserinfo(request));
            log.setContent(JSON.toJSONString(module));
            log.setCreatedate(new Timestamp(System.currentTimeMillis()));
            WebUtilify.WriteLog(log, logsService);
        }
        ret = WebUtilify.ReturnJsoninfo(errstr);
        return ret;
    }

    @RequestMapping(value = "/listdata", method = RequestMethod.GET)
    public String listdata(final HttpServletRequest request)
            throws Exception {
        int pagesize = WebUtilify.parseInt(request.getParameter("rows"), 15);
        int pageindex = WebUtilify.parseInt(request.getParameter("page"), 1);
        String name = request.getParameter("name");
        ListGageModule datamodule = new ListGageModule<>();
        datamodule.setPagesize(pagesize);
        datamodule.setPageindex(pageindex);
        Device device = new Device();
        device.setDevicename(name);
        moduleService.getPageByExampleLike(device, datamodule);
        Map<String, Object> info = new HashMap<>();
        info.put("records", datamodule.getTotalcount());
        info.put("total", datamodule.getPagecount());
        info.put("rows", datamodule.getList());
        String ret = JSON.toJSONString(info, SerializerFeature.DisableCircularReferenceDetect);// JSONArray.toJSONString(datamodule);
        return ret;
    }

    @RequestMapping(value = "/typelistdata", method = RequestMethod.GET)
    public String typelistdata(final HttpServletRequest request)
            throws Exception {
        int pagesize = WebUtilify.parseInt(request.getParameter("rows"), 15);
        int pageindex = WebUtilify.parseInt(request.getParameter("page"), 1);
        String name = request.getParameter("name");
        ListGageModule datamodule = new ListGageModule<>();
        datamodule.setPagesize(pagesize);
        datamodule.setPageindex(pageindex);
        Devicetype devicetype = new Devicetype();
        devicetype.setDevicetype(name);
        devicetypeService.getPageByExampleLike(devicetype, datamodule);
        Map<String, Object> info = new HashMap<>();
        info.put("records", datamodule.getTotalcount());
        info.put("total", datamodule.getPagecount());
        info.put("rows", datamodule.getList());
        String ret = JSON.toJSONString(info);// JSONArray.toJSONString(datamodule);
        return ret;
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public String del(final HttpServletRequest request) {
        String ret = "";
        String errstr = "";
        try {
            String delid = request.getParameter("sn");
            if (delid != null)
                this.moduleService.deleteByIdT(delid);
            else {
                errstr = "传递参数有误";
            }
            Syslog log = new Syslog();
            log.setTitle("删除设备信息");
            log.setSysuserByUserid(WebUtilify.LoginUserinfo(request));
            log.setContent(delid.toString());
            log.setCreatedate(new Timestamp(System.currentTimeMillis()));
            WebUtilify.WriteLog(log, logsService);
        } catch (Exception ex) {
            //logger.error(ex,"editChannel","更新渠道错误","");
        }
        ret = WebUtilify.ReturnJsoninfo(errstr);
        return ret;
    }

    @RequestMapping(value = "/getmodule", method = RequestMethod.GET)
    public String getmodule(final HttpServletRequest request)
            throws Exception {
        String sn = request.getParameter("sn");
        Device module = this.moduleService.get(sn);
        Map<String, Object> info = new HashMap<>();
        info.put("module", module);
        return JSON.toJSONString(info);
    }

    @RequestMapping(value = "/senddata", method = RequestMethod.POST)
    public String senddata(final HttpServletRequest request)
            throws Exception {
        String errstr = "";
        String sn = request.getParameter("sn");
        String datainfo = request.getParameter("datainfo");
        if (sn != null && !sn.equals("") && datainfo != null && !datainfo.equals("")) {
            Device module = moduleService.get(sn);
            if (module != null) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(new Date());
                cal.add(Calendar.MINUTE, 10);//10分钟

                String ckey = MD5ArithmeticUtils.getMd5(sn + datainfo + WebUtilify.ClientCkey);
                Map<String, Object> info = new HashMap<>();
                info.put("sn", sn);
                info.put("data", datainfo);
                info.put("expire", 3000);
                info.put("key", ckey);
                info.put("method", "send");

                //这里设终端接口提交数据,返回消息id号和结果值
                Devicedata devdata = new Devicedata();
//                devdata.setMetadata(JSON.toJSONString(info));
                devdata.setCreatedate(new Timestamp(System.currentTimeMillis()));
                this.devdataService.insertT(devdata);


            }
        } else {
            errstr = "参数错误001";
        }
        String restr = WebUtilify.ReturnJsoninfo(errstr);
        return restr;
    }

    @RequestMapping(value = "/cannelsn", method = RequestMethod.POST)
    public String cannelsn(final HttpServletRequest request)
            throws Exception {
        String errstr = "";
        String sn = request.getParameter("sn");
        if (sn != null && !sn.equals("")) {
            Device module = moduleService.get(sn);
            if (module != null) {
                Map<String, Object> info = new HashMap<>();
                info.put("sn", sn);
                Devicedata devdata = new Devicedata();
//                devdata.setMetadata(JSON.toJSONString(info));
                devdata.setCreatedate(new Timestamp(System.currentTimeMillis()));
                this.devdataService.insertT(devdata);

            }
        } else {
            errstr = "参数错误001";
        }
        String restr = WebUtilify.ReturnJsoninfo(errstr);
        return restr;
    }

    private Device GetDevice(String sn) throws Exception {
        return moduleService.get(sn);
    }

    @RequestMapping(value = "/syncDevice", method = RequestMethod.GET)
    public String syncDevice(final HttpServletRequest request)
            throws Exception {
        String ret = "";
        String errstr = "";
        Map<String, Device> map = DeviceCache.getInstance();
        List<Device> list = moduleService.getList();
        for (Device device : list) {
            map.put(device.getSn(), device);
        }
        ret = WebUtilify.ReturnJsoninfo(errstr);
        return ret;
    }

}